package com.netease.nim.demo.session.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.NewActionHelp;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.contact.cache.TeamMemberInfoCache;
import com.netease.nim.demo.main.fragment.ContactsFragment;
import com.netease.nim.demo.main.model.Extras;
import com.netease.nim.demo.session.activity.AbsBaseMessageActivity.TitleView;
import com.netease.nim.demo.team.activity.TeamNicknameActivity;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.shwread.android.qysw.activity.NewInteractionAtlasSeeActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.TeamMemberX;
import logic.constants.DefaultConsts;


/**
 * 点对点聊天界面
 * Created by huangjun on 2015/2/1.
 */
public class P2PMessageActivity
        extends
        AbsMessageActivity
        implements
        TitleView
{
	public static final int ACTIVITY_RESULT = 0x05;
	
	private static Intent   intentInfo;
	private static String   nickName;

	public static void start(Context context, String contactid) {
		start(context, contactid, null);
	}
	
	public static void start(Context context, String contactid, String name) {
		start(context, contactid, name, false);
	}
	
	public static void start(Context context, String contactid, String name, boolean clearTop) {
		Intent intent = new Intent();
		intent.putExtra(Extras.EXTRA_ACCOUNT, contactid);
		intent.setClass(context, P2PMessageActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		if (clearTop)
		{
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		}
		if (TextUtils.isEmpty(name))
		{
			TeamMemberX bean = TeamMemberInfoCache.getInstance().getTeammMemberInfo(contactid);
			if (null != bean)
			{
				if (!TextUtils.isEmpty(bean.getStaffName()))
				{
					nickName = bean.getStaffName();
				}
				else if (!TextUtils.isEmpty(bean.getNickName()))
				{
					nickName = bean.getNickName();
				}
				else
				{
					nickName = bean.getAccount();
				}
			}
		}
		else
		{
			nickName = name;
		}
		((Activity) context).startActivityForResult(intent, TeamNicknameActivity.REQ_CODE_TEAM_NAME);
	}
	
	//	
	//	public static void start(Context context, String contactid, Intent extras) {
	//		start(context, contactid, extras, false);
	//	}
	//	
	//	public static void start(Context context, String contactid, Intent extras, boolean clearTop) {
	//		Intent intent = new Intent();
	//		intent.putExtra(Extras.EXTRA_ACCOUNT, contactid);
	//		intent.setClass(context, P2PMessageActivity.class);
	//		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	//		if (clearTop)
	//		{
	//			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	//		}
	//		if (extras != null)
	//		{
	//			intent.putExtras(extras);
	//			if (extras.getExtras().containsKey(DefaultConsts.TO_P2P_PAGE_TAG) && extras.getExtras().containsKey(DefaultConsts.TO_P2P_PAGE_INFO))
	//			{
	//				if (extras.getExtras().getInt(DefaultConsts.TO_P2P_PAGE_TAG) == DefaultConsts.TO_P2P_PAGE_FROM_TEAM_INFO)
	//				{
	//					nickName = extras.getExtras().getString(DefaultConsts.TO_P2P_PAGE_INFO);
	//				}
	//				else if (extras.getExtras().getInt(DefaultConsts.TO_P2P_PAGE_TAG) == DefaultConsts.TO_P2P_PAGE_FROM_TEAM_MSG)
	//				{
	//					nickName = extras.getExtras().getString(DefaultConsts.TO_P2P_PAGE_INFO);
	//				}
	//				else if (extras.getExtras().getInt(DefaultConsts.TO_P2P_PAGE_TAG) == DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER)
	//				{
	//					nickName = extras.getExtras().getString(DefaultConsts.TO_P2P_PAGE_INFO);
	//				}
	//			}
	//		}
	//		if(TextUtils.isEmpty(nickName)){
	//			TeamMemberX bean = TeamMemberInfoCache.getInstance().getTeammMemberInfo(contactid);
	//			if(null!=bean) nickName = TextUtils.isEmpty(bean.getNickName()) ? bean.getAccount() : bean.getNickName();
	//		}
	//		((Activity) context).startActivityForResult(intent, TeamNicknameActivity.REQ_CODE_TEAM_NAME);
	//	}
	
	@Override
	protected int getResId() {
		return R.layout.message_activity;
	}
	
	@Override
	public SessionTypeEnum getSessionTypeEnum() {
		return SessionTypeEnum.P2P;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestBuddyInfo();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == P2PInfoActivity.P2PREQUEST_CODE && resultCode == Activity.RESULT_OK)
		{
			String reason = data.getStringExtra(P2PInfoActivity.RESULT_EXTRA_REASON);
			if (reason != null && reason.equals(P2PInfoActivity.RESULT_EXTRA_REASON_CLEAR))
			{
				items.clear();
				adapter.notifyDataSetChanged();
			}
		}
		if (requestCode == TeamNicknameActivity.REQ_CODE_TEAM_NAME && null != data)
		{
			ContactsFragment.UPDATE_NICK_NAME = data.getStringExtra(TeamNicknameActivity.EXTRA_NAME);
			setResult(RESULT_OK, data);
		}
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		//音视频通话信息刷新
		resetMessageLoadStatus();
		loadMessageFromDB(LOAD_MESSAGE_COUNT, true);
	}

	@Override
	public boolean isTeam() {
		return false;
	}

	private void requestBuddyInfo() {
		setTitle(nickName);
		setTitleView(this);
		//		setTitleName();
		//		if (!ContactDataCache.getInstance().hasBuddy(receiverid))
		//		{
		//			contactHttpClient.getUserInfo(receiverid, new IContactHttpCallback<Buddy>()
		//			{
		//				@Override
		//				public void onSuccess(Buddy buddy) {
		//					ContactDataCache.getInstance().addOrUpdateBuddy(buddy);
		//					setTitle(buddy.getDisplayname());
		//				}
		//				
		//				@Override
		//				public void onFailed(int code, String errorMsg) {
		//					setTitle("");
		//				}
		//			});
		//		}
	}
	
	private void setTitleName() {
		ArrayList<String> al = new ArrayList<String>();
		al.add(receiverid);
		NewActionHelp.qryStaffInfoByAccIds(context, al.toString(), new GetInfoHandler());
	}
	
	private long typingTime = 0;
	
	@Override
	protected void sendTypingCommand() {
		if (System.currentTimeMillis() - typingTime > 5000L)
		{
			typingTime = System.currentTimeMillis();
			CustomNotification command = new CustomNotification();
			command.setSessionId(receiverid);
			command.setSessionType(getSessionTypeEnum());
			
			JSONObject json = new JSONObject();
			json.put("id", "1");
			command.setContent(json.toString());
			
			NIMClient.getService(MsgService.class).sendCustomNotification(command);
		}
	}
	
	@Override
	public void onAtlasPressed(String imagelist) {
		String[] strArray = null;
		strArray = imagelist.split(",");
		final ArrayList<String> List = new ArrayList<String>();
		for (String url : strArray)
		{
			List.add(url);
		}
		Intent AtlasSeeIntent = new Intent();
		AtlasSeeIntent.setClass(this, NewInteractionAtlasSeeActivity.class);
		AtlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, List);
		AtlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
		startActivity(AtlasSeeIntent);
	}
	
	class GetInfoHandler
	        extends
	        ObjectHttpResponseHandler<List<TeamMemberX>>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			Logger.e(responseString);
			setTitle("聊天");
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, List<TeamMemberX> object, String responseString) {
			Logger.i(responseString);
			if (object != null)
			{
				if (!logic.util.Utils.isEmpty(object.get(0).getNickName()))
				{
					setTitle(object.get(0).getNickName());
				}
				else
				{
					setTitle("聊天");
				}
			}
			else
			{
				setTitle("聊天");
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<List<TeamMemberX>>()
			{
			}.getType();
		}
		
	}
	
	@Override
	public void onHeadImagePressed(Object item) {
		
	}
	
	@Override
	public void clickRightbutton(String receiverid) {
		P2PInfoActivity.startForTeamInfo(context, receiverid);
	}
	
	@Override
	public void onHeadImageLongPressed(Object item) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
